﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using CreaMotion.Interfaces;

namespace CreaMotion.Connectors
{
   public static class ConnectorManager
    {
        public static NHibernate.ISession CurrentNHibernateSession = null;
        public static IDBConnector CurrentConnection = null;

        #region GetConnectors

        public static List<IDBConnector> GetConnectors()
        {
            return (from ConnType in GetConnectorTypes()
                    select (IDBConnector)Activator.CreateInstance(ConnType)).ToList();
        }

        #endregion

        #region GetConnector
       
        public static IDBConnector GetConnector(String ConnectorName)
        {
            return (from Conn in GetConnectors() 
                    where Conn.AboutConnector().SupportedDatabaseSystem == ConnectorName
                    select Conn).First();
        }

        #endregion

        #region GetConnectorsInformation

        public static Dictionary<String, Interfaces.About> GetConnectorsInformation()
        {
            Dictionary<String, About> ReturnData = new Dictionary<string, About>();
            List<Type> myConnectors = GetConnectorTypes();

            foreach (Type item in myConnectors)
            {
                IDBConnector TempObj = Activator.CreateInstance(item) as IDBConnector;
                ReturnData.Add(item.FullName, TempObj.AboutConnector());
                
                TempObj = null;
            }

            return ReturnData;
        }

        #endregion

        #region GetConnectorInformation

        public static About GetConnectorInformation(String ConnectorName)
        {
            return GetConnectorsInformation()[ConnectorName];
        }

        #endregion

        #region GetConnectorTypes

        private static List<Type> GetConnectorTypes()
        {
            Dictionary<String, Interfaces.About> ReturnData = new Dictionary<string, About>();
            Assembly asm;

            try { asm = Assembly.GetExecutingAssembly(); }
            catch { return null; }

            return  (from typ in asm.GetTypes()
                     where typ.IsClass == true && typ.GetInterface("IDBConnector") != null
                     select typ).ToList();
        }

        #endregion
    }
}
